import React from 'react';
import ReactDOM from 'react-dom';
import '../css/style.css';
//获取图片信息相关数据
let imageDatas =require('json!../data/imageData.json');


//使用ES6箭头函数，并采用自执行函数写法，与闭包类似，通常只调用一次的函数采用此种写法
imageDatas =((imageDataArr) => {

  for(let i=0;i<imageDataArr.length;i++){

       imageDataArr[i].url = require('../images/'+imageDataArr[i].fileName);

  }

  return imageDataArr;

})(imageDatas)

//获取区间内的一个随机值

var getRangeRandom =(low,high) =>{
  return Math.ceil(Math.random()*(high-low)) + low;
}


var get30RandomRotate =() =>{

  return (Math.random()>0.5?'':'-') + Math.ceil(Math.random() * 30);

}





//单个图片组件
class ImgFigure extends React.Component {
  constructor(props){
    super(props);
    this.handleClick = this.handleClick.bind(this);


  }



  handleClick(e){

    if(this.props.arrange.isCenter){
      this.props.inverse();
    }else{
      this.props.center();
    }

    e.stopPropagation();
    e.preventDefault();
  }
  render() {

    var styleObj =null;
    if(this.props.arrange.pos){

      styleObj = this.props.arrange.pos;
    }


    if(this.props.arrange.rotate){
      (['Webkit','Moz','ms','']).forEach((value) =>{
          //这里相当于.,即是给styleObj添加新的属性,注意这里的属性名就是css中的名称,但是使用驼峰表示法
          styleObj[value + 'Transform'] = 'rotate('+this.props.arrange.rotate+ 'deg)';

      })
    }

    if(this.props.arrange.isCenter){

        styleObj.zIndex = 11;

    }

    let figureClassName = 'figure-container';

    figureClassName+=this.props.arrange.isInverse?' is-inverse' : '';


    return(

      <figure className={ figureClassName } style = { styleObj } onClick = { this.handleClick }>
       <img src ={this.props.data.url} alt={this.props.data.title} className="figure-image"/>
       <figcaption className="figure-text-container">
        <h2 className="figure-title">
          {this.props.data.title}
        </h2>
        <div className="img-back" onClick = { this.handleClick }>
          <p>
            {this.props.data.title}
          </p>
        </div>
       </figcaption>
      </figure>


    )

  }


}

class ControllerUnits extends React.Component{
  constructor(props){
    super(props);
    this.handleClick = this.handleClick.bind(this);
  }

  handleClick(e){
    if(this.props.arrange.isCenter){
        this.props.inverse()
    }else{
      this.props.center();
    }

    e.stopPropagation();
    e.preventDefault();
  }
  render(){
    let controllerClassName = 'controllerUnit';
    if(this.props.arrange.isCenter){
      controllerClassName += ' is-center';
    }
    if(this.props.arrange.isInverse){
      controllerClassName += ' is-inverse';
    }
    return(
        <span className={controllerClassName} onClick={this.handleClick}></span>
      );

  }
}

class AppComponent extends React.Component{
  constructor(props){
    super(props);
    this.Constant ={
      //中心点位置
      centerPos:{
        left:0,
        top:0
      },
      //水平方向范围
      hPosRange:{
       //左侧区域水平范围
       leftSecX:[0,0],
       //右侧区域水平范围
       rightSecX:[0,0],
       y:[0,0]
      },
      //垂直方向范围
      vPosRange:{
        x:[0,0],
        y:[0,0]
      }
    };

    this.state = {
      imgsArrangeArr: []
    }
  }


  inverse(index){
    return () =>{
      let imgsArrangeArr = this.state.imgsArrangeArr;

      imgsArrangeArr[index].isInverse = !imgsArrangeArr[index].isInverse;

      //更改完毕后一定要记住setState，这样才能重新出发render,进行绘制
      this.setState({

              imgsArrangeArr : imgsArrangeArr

              });

    }
  }

  //重新布局所有图片
  rearrange(centernIndex){
    let imgsArrangeArr = this.state.imgsArrangeArr,
        //中心点坐标信息
        centerPos = this.Constant.centerPos,
        //水平方向上的坐标信息
        hPosRange = this.Constant.hPosRange,
        //垂直方向上的坐标信息
        vPosRange = this.Constant.vPosRange,
        //中心点的具体信息
        centerLeft = centerPos.left,

        centerTop = centerPos.top,

        //水平方向上的具体信息

        leftSecX = hPosRange.leftSecX,

        rightSecX= hPosRange.rightSecX,

        hPosRangeY = hPosRange.y,

        //垂直方向上的具体信息

        vPosRangeX = vPosRange.x,

        vPosRangeY = vPosRange.y,

        //包含顶部信息图片的数组

        imgArrangeTopArr = [],

        //位于顶部的图片数量,取0或者1
        topNum = Math.floor(Math.random()*2),

        //首先取出要居中的图片信息

        imgsArrangeCenterArr = imgsArrangeArr.splice(centernIndex,1);


        imgsArrangeCenterArr[0] = {

            pos: centerPos,

            rotate : 0,

            isInverse : false,

            isCenter : true


        }

        //取出位于上侧的图片信息,这里为什么要减topNum，还不太明白

        var TopIndex = Math.floor(Math.random()*(imgsArrangeArr.length - topNum ));

        imgArrangeTopArr = imgsArrangeArr.splice(TopIndex,topNum);

        imgArrangeTopArr.forEach((value,index) =>{

            imgArrangeTopArr[index] = {

                pos:{

                  left:getRangeRandom(vPosRangeX[0],vPosRangeX[1]),

                  top:getRangeRandom(vPosRangeY[0],vPosRangeY[1])


                },

                rotate:get30RandomRotate(),

                isInverse : false,

                isCenter : false

            }

        })
        //布局左右侧的图片
       for(let i =0,j = imgsArrangeArr.length,k = j/2;i<j;i++){

          let ROLSecX = null;

          //当i小于k时给左侧图片赋值
          if(i<k){

            ROLSecX=leftSecX

          }else{

            ROLSecX =rightSecX
          }


          imgsArrangeArr[i] = {

            pos:{

              left:getRangeRandom(ROLSecX[0],ROLSecX[1]),

              top:getRangeRandom(hPosRangeY[0],hPosRangeY[1])


            },

            rotate:get30RandomRotate(),

            isInverse : false,

            isCenter : false

          }

       }


            if(imgArrangeTopArr && imgArrangeTopArr[0]){

              imgsArrangeArr.splice(TopIndex,0,imgArrangeTopArr[0]);

            }

            imgsArrangeArr.splice(centernIndex,0,imgsArrangeCenterArr[0]);

            //把imgsArrangeArr加入到state中
            this.setState({

              imgsArrangeArr : imgsArrangeArr

              })


  }

  //定位中心的函数
  center(index){
    return () =>{
      this.rearrange(index);
    }
  }
  //组件加载以后调用该方法
  componentDidMount(){
    //stage相关所有变量
    let stageDom = ReactDOM.findDOMNode(this.refs.stage),
        stageWidth = stageDom.scrollWidth,
        stageHeight = stageDom.scrollHeight,
        halfStageWidth = Math.ceil(stageWidth/2),
        halfStageHeight = Math.ceil(stageHeight/2);
    //imageFigure相关所有变量
    let imgDom = ReactDOM.findDOMNode(this.refs.imageFigure0),
        imgWidth = imgDom.scrollWidth,
        imgHeight = imgDom.scrollHeight,
        halfImgHeight = Math.ceil(imgHeight/2),
        halfImgWidth = Math.ceil(imgWidth/2);

        //求得中心点位置
        this.Constant.centerPos = {
          left:halfStageWidth-halfImgWidth,
          top:halfStageHeight-halfImgHeight
        }
        //左侧区域相关参数赋值
        this.Constant.hPosRange.leftSecX[0] = -halfImgWidth;
        this.Constant.hPosRange.leftSecX[1] = halfStageWidth - halfImgWidth*3;
        //右侧区域相关参数赋值
        this.Constant.hPosRange.rightSecX[0] = halfImgWidth + halfStageWidth;
        this.Constant.hPosRange.rightSecX[1] = stageWidth - halfImgWidth;
        //左右侧区域的垂直方向参数
        this.Constant.hPosRange.y[0] = -halfImgHeight;
        this.Constant.hPosRange.y[1] = stageHeight - halfImgHeight;
        //上方区域相关参数
        this.Constant.vPosRange.x[0] = halfStageWidth- imgWidth;
        this.Constant.vPosRange.x[1] = halfStageWidth + imgWidth;

        this.Constant.vPosRange.y[0] = -halfImgHeight;
        this.Constant.vPosRange.y[1] = halfStageHeight - halfImgHeight*3;

        this.rearrange(0);



  }


  render() {

    var imageFigures = [],
        controllerUnits = [];

    //循环遍历给imageDatas添加标签

    imageDatas.forEach((value, index)=> {
      if(!this.state.imgsArrangeArr[index]){
        this.state.imgsArrangeArr[index] = {
          pos:{
            left:0,
            top:0
          },

          rotate:0,
          isInverse: false,
          isCenter: false
        }
      }
      imageFigures.push(<ImgFigure data={value} key={index} ref={'imageFigure'+index}
                                   arrange={this.state.imgsArrangeArr[index]}
                                   inverse={this.inverse(index)}
                                   center={this.center(index)}/>);

      controllerUnits.push(<ControllerUnits key={index}
                                            arrange={this.state.imgsArrangeArr[index]}
                                            inverse={this.inverse(index)}
                                            center={this.center(index)}
                                            />);



    });
    return (
     <section className="stage" ref="stage">
          <section className="stage-img">
            {imageFigures}
          </section>
          <nav className="stage-switch">
            {controllerUnits}
          </nav>
     </section>
    );
  }
}



AppComponent.defaultProps = {
};

export default AppComponent;
